import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TreeUtil {
    public static List<Integer> toList(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Queue<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        while (nodes.size() != 0) {
            TreeNode node = nodes.poll();
            if (node != null) {
                res.add(node.val);
                nodes.offer(node.left);
                nodes.offer(node.right);
            } else {
                res.add(null);
            }
        }
        for (int i = res.size() - 1; i >= 0; i--) {
            if (res.get(i) == null) {
                res.remove(i);
            } else {
                break;
            }
        }
        return res;
    }

    public static TreeNode toTree(List<Integer> tree) {
        if (tree.size() == 0) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(new TreeNode(tree.get(0)));
        TreeNode root = queue.peek();
        int i = 1;
        while (i < tree.size()) {
            TreeNode t = queue.poll();
            if (t != null) {
                TreeNode leftChild = null;
                try {
                    leftChild = new TreeNode(tree.get(i));
                } catch (NullPointerException ignored) {
                }
                i++;
                t.left = leftChild;
                queue.offer(leftChild);
                if (i < tree.size()) {
                    TreeNode rightChild = null;
                    try {
                        rightChild = new TreeNode(tree.get(i));
                    } catch (NullPointerException ignored) {
                    }
                    i++;
                    t.right = rightChild;
                    queue.offer(rightChild);
                }
            }
        }
        return root;
    }
}
